package cn.wolfcode.wolf.article.controller;


import cn.wolfcode.wolf.article.domain.Strategy;
import cn.wolfcode.wolf.article.service.StrategyCatalogService;
import cn.wolfcode.wolf.article.service.StrategyService;
import cn.wolfcode.wolf.article.utils.OssUtil;
import cn.wolfcode.wolf.core.utils.Result;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/strategies")
public class StrategyController {

    private final StrategyService strategyService;

    public StrategyController(StrategyService strategyService) {
        this.strategyService = strategyService;
    }

    @Autowired
    private StrategyCatalogService strategyCatalogService;
    @GetMapping("/query")
    public Result<Page<Strategy>> pageList(Page<Strategy> page) {
        return Result.success(strategyService.page(page));
    }


    @GetMapping("/detail")
    public Result<Strategy> getById(Long id) {
        return Result.success(strategyService.getById(id));
    }

    @PostMapping("/save")
    public Result<?> save(Strategy dest) {
        strategyService.save(dest);
        return Result.success();
    }

    @PostMapping("/uploadImg")
    public JSONObject uploadIm(MultipartFile upload) {
        JSONObject result = new JSONObject();
        if (upload == null) {
            result.put("uploaded", 0);
            JSONObject error = new JSONObject();
            error.put("message", "请选择要上传的文件!");
            result.put("error", error);
            return result;
        }
        // 调用阿里云 OSS 工具类进行文件上传
        // 解决文件名重复问题
        // 1. 直接使用 UUID 替换原始文件名
        // 2. 在原始文件名后面拼接时间戳
        String fileName =
            upload.getOriginalFilename().substring(0, upload.getOriginalFilename().lastIndexOf(".")) + "_" + System.currentTimeMillis();
        // 返回阿里云可访问的 url 地址
        String url = OssUtil.upload("images", fileName, upload);
        result.put("uploaded", 1);
        result.put("fileName", upload.getOriginalFilename());
        result.put("url", url);
        return result;
    }
    @PostMapping("/update")
    public Result<?> updateById(Strategy dest) {
        strategyService.updateById(dest);
        return Result.success();
    }

    @PostMapping("/delete/{id}")
    public Result<?> deleteById(@PathVariable Long id) {
        strategyService.removeById(id);
        return Result.success();
    }
}
